package com.chuhe.starry.websocket.netty;

import com.chuhe.common.domain.dto.TokenUserInfoDto;
import com.chuhe.common.utils.RedisComponet;
import com.chuhe.common.utils.StringTools;
import com.chuhe.starry.websocket.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 业务处理
 * @Author: 楚河
 * @Date: 2025年05月18日20:28
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    public static final int INT_2 = 2;

    @Autowired
    private RedisComponet redisComponet;
    @Autowired
    private ChannelContextUtils channelContextUtils;

    /**
     * 有新的连接就会调用此方法
     * 当通道就绪后会调用此方法，通常我们会在这里做一些初始化操作
     * @Author: 楚河
     * @Date: 2025-05-18 20:36
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有新的连接建立: {}", ctx.channel().id());
    }

    /**
     * 有连接断开 就会调用此方法
     * 当通道不再活跃时（连接关闭）会调用此方法，我们可以在这里做一些清理工作
     * @Author: 楚河
     * @Date: 2025-05-18 20:36
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
        channelContextUtils.removeContext(channel);
        log.info("用户< {} >连接已断开。。。",userId);
    }

    /**
     * 处理入口
     * @Author: 楚河
     * @Date: 2025-05-18 20:35
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame txt) throws Exception {
        //接收心跳
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
//        log.info("收到用户< {} >的消息：{}",userId,txt.text());
        redisComponet.saveUserHeartBeat(userId);

    }

    /**
     * 握手认证
     * @Author: 楚河
     * @Date: 2025-05-19 20:09
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 检查事件是否为WebSocket握手完成事件
        if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            // 将事件转换为握手完成事件对象
            WebSocketServerProtocolHandler.HandshakeComplete handshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String url = handshakeComplete.requestUri();
            String token = getToken(url);
            if(token == null){
                ctx.channel().close();//关闭通道
                return;
            }
            //获取redis里的正确token去比对
            TokenUserInfoDto tokenUserInfoDto = redisComponet.getTokenUserInfoDto(token);
            if(tokenUserInfoDto == null){
                ctx.channel().close();//关闭通道
                return;
            }
            channelContextUtils.addContext(tokenUserInfoDto.getUserId(),ctx.channel());
        }
    }
    /**
     * 根据拦截到的url获取token
     * @Author: 楚河
     * @Date: 2025-05-19 20:12
     */
    private String getToken(String url) {
        // ws?token = fafsasda
        if (StringTools.isEmpty(url) || url.indexOf("?") == -1) {
            return null;
        }
        String[] split = url.split("\\?");
        if(split.length < INT_2){
            return null;
        }
        String[] split1 = split[1].split("=");
        if(split1.length < INT_2){
            return null;
        }
        return split1[1];
    }
}
